<template>
  <div style="width: 100%; height: 30px"></div>
  <div class="member">
    <div class="wrapper-title">
      <span class="title">{{$t('员工')}}（{{ total }}{{$t('人')}}）</span>
      <div class="icon-wrapper">
        <div class="icon-item">
          <span
                  class="iconfont icon-tianjiahaoyou"
                  @click="openAddMember"
          ></span>
        </div>
        <div class="icon-item">
          <span class="iconfont icon-shanchu" @click="deleteAll"></span>
        </div>
        <div class="icon-item">
          <span class="iconfont icon-shangchuan1" @click="exportAll"></span>
        </div>
      </div>
    </div>
    <div class="filters">
      <el-input
              v-model="keywords"
              style="width: 413px; height: 46px"
              size="large"
              :placeholder="$t('请输入搜索内容')"
              :suffix-icon="Search"
              clearable
              @input="fetchData"
      />
    </div>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('姓名')" property="personName" />
      <el-table-column :label="$t('手机号')" property="phone" width="140" />
      <el-table-column :label="$t('邮箱')" property="email" width="200" />
      <el-table-column :label="$t('部门/班级')" property="department" width="200" />
      <el-table-column :label="$t('操作')" width="240">
        <template #default="scope">
          <div class="actions">
            <span
                    class="iconfont icon-bianji"
                    @click="editAddMember(scope.row.id)"
            ></span>
            <span
                    class="iconfont icon-zhuyi"
                    @click="openViolationRecord(scope.row.id)"
            ></span>
            <span
                    class="iconfont icon-shanchu"
                    @click="deleteItem(scope.row.id)"
            ></span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="total > 0">
      <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[100, 200, 300, 400]"
              :size="size"
              :disabled="disabled"
              :background="background"
              layout="prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
      />
      <span class="total">{{$t('共')}} {{ total }} {{$t('条')}}</span>
    </div>
    <!-- 人员录入 -->
    <AddMember
            v-if="addMemberDialog"
            :id="id"
            @closeAddMember="closeAddMember"
            @refreshData="fetchData"
    ></AddMember>
    <!-- 违规记录 -->
    <ViolationRecord
            v-if="violationRecordDialog"
            :id="id"
            @closeViolationRecord="closeViolationRecord"
    ></ViolationRecord>
  </div>
</template>

<script>
import { getStuff, deleteStuff, exportStuff } from '@/api/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import AddMember from './components/addMember.vue';
import ViolationRecord from './components/violationRecord.vue';
export default {
  name: 'Member',
  props: {
    addFlag: {
      type: Number,
      default() {
        return 0;
      }
    }
  },
  watch: {
    addFlag(nv) {
      console.log(nv)
      this.addMemberDialog = true
    }
  },
  components: {
    AddMember,
    ViolationRecord,
  },
  data() {
    return {
      id: null,
      addMemberDialog: false,
      violationRecordDialog: false,
      Search,
      keywords: '',
      total: null,
      currentPage: 1,
      pageSize: 20,
      size: 'default',
      disabled: false,
      background: true,
      tableData: [],
      selectedItems: []
    };
  },
  mounted() {
    this.fetchData(); // 初始化加载数据
  },
  methods: {
    handleSelectionChange(selectedItems){
      this.selectedItems = selectedItems;
    },
    // 获取员工数据
    async fetchData() {
      const params = {
        page: this.currentPage,
        count: this.pageSize,
        keywords: this.keywords,
      };
      try {
        const {data} = await getStuff({ ...params }); // 使用封装的 API 请求方法
        if (data.code === 0) {
          this.tableData = data.data.records; // 更新表格数据
          this.total = +data.data.total; // 更新总数据条数
          this.pageSize = +data.data.size; // 设置每页条数
        }
      } catch (error) {
        console.log(error);
      }
    },
    openViolationRecord(id) {
      this.id = id;
      this.violationRecordDialog = true;
    },
    closeViolationRecord() {
      this.violationRecordDialog = false;
    },
    openAddMember() {
      this.id = null;
      this.addMemberDialog = true;
    },
    editAddMember(id) {
      this.id = id;
      this.addMemberDialog = true;
    },
    closeAddMember() {
      this.addMemberDialog = false;
    },
    exportAll() {
      ElMessageBox.confirm(this.$t('是否要批量导出?'), this.$t('批量导出'), {
        confirmButtonText: this.$t('导出'),
        cancelButtonText: this.$t('取消'),
        type: 'warning',
      })
          .then(async () => {
            try {
              const data = await exportStuff();
              let blob = new Blob([data.data], {
                type: data.data.type
              });
              let objectUrl = URL.createObjectURL(blob);
              const elink = document.createElement("a");
              elink.download = this.$t('人员表');
              elink.style.display = "none";
              elink.href = objectUrl;
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href);
              document.body.removeChild(elink);
              ElMessage({
                type: 'success',
                message: this.$t('导出成功'),
              });
            } catch (error) {
              console.log(error);
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消导出'),
            });
          });
    },

    deleteItem(id) {
      ElMessageBox.confirm(
          this.$t('删除该人员信息后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteStuff([id]); // 使用数组传递单个 ID
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData(); // 删除后刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.log(error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },

    deleteAll() {
      const selectedIds = this.selectedItems.map(
          (item) => item.id,
      );

      if (selectedIds.length === 0) {
        ElMessage({
          type: 'warning',
          message: this.$t('请选择要删除的人员！'),
        });
        return;
      }

      ElMessageBox.confirm(
          this.$t(`已选择`) + ' ' + selectedIds.length + ' ' + this.$t('条人员数据，删除人员信息后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteStuff(selectedIds); // 使用数组传递多个 ID
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData(); // 删除后刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.log(error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },
    // 翻页处理
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData(); // 翻页时重新请求数据
    },

    // 每页显示条数变化处理
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData(); // 每页条数变化时重新请求数据
    },
  },
};
</script>

<style lang="scss" scoped>
.member {
  .wrapper-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-weight: 500;
      font-size: 24px;
      color: #ffffff;
      line-height: 38px;
    }

    .icon-wrapper {
      display: inline-flex;

      .icon-item {
        width: 30px;
        height: 30px;
        background: rgba(31, 210, 103, 0.16);
        border-radius: 50%;
        text-align: center;
        line-height: 30px;
        margin-right: 17px;
        cursor: pointer;
        transition: 0.3s ease;

        .iconfont {
          color: #fff;
        }

        &:hover {
          background: $color;
        }
      }
    }

    .sub {
      font-weight: 400;
      font-size: 14px;
      color: #eaeaea;
      margin-left: 24px;
    }

    .more {
      float: right;
      font-weight: 400;
      font-size: 16px;
      color: #dfdfdf;
      display: flex;
      align-items: center;

      i {
        font-size: 10px;
        margin-left: 10px;
      }
    }
  }

  .filters {
    margin-bottom: 30px;
  }

  .actions {
    .iconfont {
      font-size: 20px;
      transition: 0.3s ease;
      margin-right: 26px;
      cursor: pointer;

      &:hover {
        color: $color;
      }
    }
  }
}
</style>
